import { Component, OnInit, Input, Output, EventEmitter, OnChanges } from '@angular/core';

@Component({
  selector: 'app-stars',
  templateUrl: './stars.component.html',
  styleUrls: ['./stars.component.css']
})
export class StarsComponent implements OnInit, OnChanges {

  @Input()
  private rating: number;
  // 命名规则必须和@Input的一样 再加Change 才可以实现双向绑定
  @Output()
  private ratingChange: EventEmitter<number> = new EventEmitter<number>();
  private stars: Array<boolean> = new Array<boolean>();
  @Input()
  private readOnly: Boolean = true;

  constructor() { }
  ngOnInit() { }

  /**
   * ngOnChanges() 对有@Input注解的成员变量有变化检测
   */
  ngOnChanges() {
    // console.log('ngOnChanges() 执行了');
    this.stars = [];
    for (let i = 1; i <= 5; i++) {
      // true = 空星星，false = 实星星
      this.stars.push(i > this.rating + 0.5);
    }
  }

  /**
   * 点击修改星星数
   */
  clickStar(num: number) {
    if (!this.readOnly) {
      // this.rating 改变会自动调用 ngOnChanges()
      this.rating = num + 1;
      // 发射事件
      this.ratingChange.emit(this.rating);
    }
  }
}
